/**
 * 该js为所有页面都必须加载的js
 * 可以用于全局添加某功能
 */

import "./ajax_pack.js";
import { Base64 } from '@common/base64.min.js';
import Vue from 'vue/dist/vue.esm.js';

$.cookie.json = true;
$.extend({
    appendLoad: function(dom = 'body',text = '正在加载....', width = '') {
        let loadHTML = `
            <div class='load' style="display:none;">
                <div class='box'>
                    <img class='img' src='${require('@assets/imgs/load.svg')}' style='width:${width};height:${width};' />
                    <span class='text'>${text}</span>
                </div>
            </div>
        `;
        $(dom).append(loadHTML);
    },
    showLoad: function(dom = 'body',text = '正在加载....', width = '') {
        if (dom !== 'body')  {
            $.appendLoad(dom, text, width);
        }
        $(dom + '>.load').show();
    },
    hideLoad: function() {
        $('div.load').hide();
    },
    WebSocket: function(opts) {
        if(window.MozWebSocket || window.WebSocket) {
            window.WebSocket = window.MozWebSocket || window.WebSocket;

            let wsOpts = Object.assign({
                url: '',
                open: function() {},
                message: function() {},
                close: function() {},
                error: function() {}
            }, opts);
            
            let ws = new WebSocket(wsOpts.url);
            ws.onopen = function(ev) {
                console.log('WS请求正在发送....');
                wsOpts.open(ev);
            };
            ws.onmessage = function(ev) {
                wsOpts.message(ev);
            };
            ws.onclose = function(ev) {
                console.log('WS请求关闭....');
                wsOpts.close(ev);
            };
            ws.onerror = function(ev) {
                console.log('WS请求异常....');
                wsOpts.error(ev);
            };

            return ws;
        } else {
            alert("您的浏览器不支持WebSocket！请更换浏览器！");
        }
    },
    /** 是否为手机号
        * params - str: Number || String
        * return: Boolean
        */
    testMobile: function(str) {
        if (!new RegExp(/^1[3456789]\d{9}$/).test(str)) {
           return false;
        } else {
           return true;
        }
    },
    /** 是否邮箱
        * params - str: Number || String
        * return: Boolean
        */
    testMail: function(str) {
        if (!new RegExp(/^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/).test(str)) {
           return false;
        } else {
           return true;
        }
    },
    /** 是否为不含特殊符号的密码，且长度在6-16位间
        * params - str: Number || String
        * return: Boolean
        */
    testPassword: function(str) {
        if (str.length > 5 && str.length < 17 && new RegExp(/^[0-9a-zA-Z]*$/g).test(str)) {
            return true;
        } else {
            return false;
        }
    },
    /** 是否为准确的身份证号
        * params - str: Number || String
        * return: Boolean
        */
    $testID: function(str) {
        if (new RegExp(/^[1-9][0-7]\d{4}((19\d{2}(0[13-9]|1[012])(0[1-9]|[12]\d|30))|(19\d{2}(0[13578]|1[02])31)|(19\d{2}02(0[1-9]|1\d|2[0-8]))|(19([13579][26]|[2468][048]|0[48])0229))\d{3}(\d|X|x)?$/).test(str)) {
            return true;
        } else {
            return false;
        }
    },
    /** 是否不是undefined
        * params : All
        * return: Boolean
        */
    $testNotUndefined: function() {
        let index = 0;
        let result = true;
        do {
            if (arguments[index] === undefined) {
                result = false;
                break;
            }
            index++;
        } while (index < arguments.length);
        return result;
    },
    /** 隐藏中间位数
        * params - nums: Array || String (需要隐藏的值)
        * return: String
        */
    $hideTheMiddle: function(str) {
        str = str ? str.toString() : str;
        let result;
        if (str && str.indexOf('*') > -1) {
            result = str;
        } else if ($.$testID(str)) {
            result = str.substr(0, 6) + '****' + str.substr(14, str.length);
        } else if (str) {
            result = str.substr(0, 3) + '****' + str.substr(7, str.length);
        } else {
            result = str;
        }
        return result;
    },
    /** 数字前面加零
        * params - nums: Array || String (判断数字小于10则加0，如果数据较多则用数组的形式传值)
        * return: Array || String
        */
    $addZero: function(nums) {
        if (Array.isArray(nums)) {
            let index = 0;
            let result = [];
            do {
                let str = nums[index] < 10 ? '0' + nums[index] : nums[index];
                result.push(str.toString());
                index++;
            } while (index < nums.length);

            return result;
        } else {
            if (nums < 10) { return '0' + nums; }
            else { return nums.toString(); }
        }
    },
    /** 格式化时间戳
        * params - Date: number (时间戳)
        * params - hasTime: Boolean (是否包含时分秒)
        * params - symbol: String (年月日之间的连接符号，默认/)
        * return: String
        */
    $getFormatMD: function(date, hasTime, symbol) {
        if (!symbol) symbol = '/';
        date = typeof(date) === 'number' ? date : Date.parse(date);
        let dateString = new Date(date);
        let dateArr = [
            dateString.getFullYear(),
            (dateString.getMonth() + 1),
            dateString.getDate(),
            dateString.getHours(),
            dateString.getMinutes(),
            dateString.getSeconds()
        ];
        dateArr = $.$addZero(dateArr);
        
        if (dateArr[0] === 'NaN') {
            return '暂无';
        } else {
            return hasTime ? dateArr.splice(0, 3).join(symbol) + ' ' + dateArr.join(':') : dateArr.splice(0, 3).join(symbol);
        }
    },
    /** 时间戳转为倒计时
        * params - setupDate: number (设定时间的时间戳)
        * params - stopDate: number (结束时间的时间戳)
        * hasDay - stopDate: boolean (是否返回天数，没有则用小时计算)
        * return: Array
        */
    $getCountDown: function(date, hasDay) {
        date = Math.floor(date / 1000);

        if (date > 0) {
            let d = Math.floor(date / 86400);
            let h = Math.floor((date %= 86400) / 3600);
            let m = Math.floor((date %= 3600) / 60);
            let s = date % 60;

            if (!hasDay) {
                h = d * 24 + h
                return $.$addZero([h, m, s]);
            } else {
                return $.$addZero([d, h, m, s]);
            }
        } else {
            return !hasDay ? new Array('00', '00', '00') : new Array('00', '00', '00', '00');
        }
    },
    /** 提前N天或推后N天
        * params - date: Date (日期)
        * params - num: Number (提前或推后的秒数)
        * return: Number
        */
    $calcDate: function(date, num, format) {
        if(!date || Date.parse(date).toString().length !== 13) date = new Date();
        if(typeof(date) === 'string') date = new Date(date);
        date.setSeconds(date.getSeconds() + Number(num));
        return format ? $.$getFormatMD(date, format[0], format[1]) : Date.parse(date);
    },
    /* BASE64加密存取cookie，使用方法同JQ cookie */
    $cookieProtect: function(key, val, config) {
        if (val === undefined) {
            const cookie = $.cookie(Base64.encode(key), val);
            if (cookie) return JSON.parse(Base64.decode($.cookie(Base64.encode(key), val)));
        } else {
            return $.cookie(Base64.encode(key), Base64.encode(JSON.stringify(val)), config);
        }
    },
    /* 删除加密后的cookie字段，使用方法同JQ cookie */
    $removeCookieProtect: function(key) {
        return $.removeCookie(Base64.encode(key));
    },
    /* localStorage进行进一步的封装 */
    $localStorage: {
        setItem: function(key, val) {
            try {
                const enableType = ['string', 'number', 'boolean', 'null', 'undefined'];
                if (enableType.indexOf(typeof(val)) === -1) val = JSON.stringify(val);
                return window.localStorage.setItem(key, val);
            } catch (err) {
                console.log(err);
            };
        },
        getItem: function(key, isObj) {
            try {
                const enableType = ['string', 'number', 'boolean', 'null', 'undefined'];
                const result = window.localStorage.getItem(key);
                return enableType.indexOf(typeof(val)) === -1 || isObj ? JSON.parse(result) : result;
            } catch (err) {
                console.log(err);
            };
        },
        removeItem: function(key) {
            try {
                return window.localStorage.removeItem(key);
            } catch (err) {
                console.log(err);
            };
        }
    },
    /* sessionStorage进行进一步的封装 */
    $sessionStorage: {
        setItem: function(key, val) {
            try {
                const enableType = ['string', 'number', 'boolean', 'null', 'undefined'];
                if (enableType.indexOf(typeof(val)) === -1) val = JSON.stringify(val);
                return window.sessionStorage.setItem(key, val);
            } catch (err) {
                console.log(err);
            };
        },
        getItem: function(key, isObj) {
            try {
                const enableType = ['string', 'number', 'boolean', 'null', 'undefined'];
                const result = window.sessionStorage.getItem(key);
                return enableType.indexOf(typeof(val)) === -1 || isObj ? JSON.parse(result) : result;
            } catch (err) {
                console.log(err);
            };
        },
        removeItem: function(key) {
            try {
                return window.sessionStorage.removeItem(key);
            } catch (err) {
                console.log(err);
            };
        }
    },
    /* 生成一个日期+五位随机数的订单 */
    $createOrder: function() {
        let date = new Date();
        let dateString = date.getFullYear().toString() + $.$addZero(date.getMonth() + 1) + $.$addZero(date.getDate()) + $.$addZero(date.getHours()) + $.$addZero(date.getMinutes()) + $.$addZero(date.getSeconds());
        return dateString + parseInt(Math.random() * (99999 - 10000) + 10000);
    },
    /* 八位数或以下阿拉伯数字转中文数字 */
    $numstoChinese: function(num) {
        let changeNum = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
        let unit = ["", "十", "百", "千", "万"];
        num = parseInt(num);
        let getWan = (temp) => {
        　　let strArr = temp.toString().split("").reverse();
        　　let newNum = "";
        　　for (var i = 0; i < strArr.length; i++) {
        　　newNum = (i == 0 && strArr[i] == 0 ? "" : (i > 0 && strArr[i] == 0 && strArr[i - 1] == 0 ? "" : changeNum[strArr[i]] + (strArr[i] == 0 ? unit[0] : unit[i]))) + newNum;
        　　}
        　 return newNum;
        }
        let overWan = Math.floor(num / 10000);
        let noWan = num % 10000;
        if (noWan.toString().length < 4) {　　　　　　noWan = "0" + noWan;　　　 }
        return overWan ? getWan(overWan) + "万" + getWan(noWan) : getWan(num);
    },
    /** 美元转为RMB（暂定*7）
        * params - val: Number (需要转换的数字，字符串只能带数字)
        * params - decimal: Number (小数点的位数)
        * return: String
        */
    $convertRMB: function(val, decimal) {
        val = Number(val);
        return val ? (val * 7).toFixed(decimal || 2) : '0.00';
    },
    /** 给数字每隔三位加逗号
        * params - num: Number (提前或推后的秒数，字符串只能带数字)
        * params - decimal: Number (小数点的位数)
        * return: String
        */
    $numberAddComma(num, decimal) {
        let val = Number(num || 0).toFixed(decimal || 2).split('.');
        num = val[0];
        let result = '';

        for (let i = 0;i < num.length;i++) {
            if (num.length > 3) {
                result = ',' + num.slice(-3) + result;
                num = num.slice(0, num.length - 3);
            } else {
                break;
            }
        }

        if (num) { result = num + result; }
        result = val[1] ? result + '.' + val[1] :  result + '.00';
        return result;
    },
    /* promise对象空数组（vue-beauty的table常用到） */
    $getPromiseNullData: function() {
        return new Promise(function(resolve) { resolve({ result: [] }); });
    },
    /** 下载canvas图片
        * params - data: Object (JQcanvas对象)
        * return: File
        */
    $downloadCanvasImg: function(data) {
        if (!data || !data.length || data.length < 0) {
            console.log('下载失败！！');
        } else {
            var dom_a = $(document.createElement('a'));
            dom_a.attr({'href': data[0].toDataURL("image/jpg"), 'download': Date.parse(new Date()) + '.jpg'});
            dom_a[0].click();
        }
    },
    /** img转为Base64
        * params - file: Object (input文件返回对象)
        * resolve: String
        */
    $imgToBase64: function(file) {
        let reader = new FileReader();
        reader.readAsDataURL(file);
        return new Promise(function(resolve) {
            reader.onload = function(ev){
                resolve(ev.target.result);
            };
            reader.onerror = function(ev){
                Vue.$notification.error({
                    message: '操作错误！！',
                    description: '读取文件失败！！',
                });
            };
        });
    },
    /** 深拷贝
        * params - obj: Object (需要拷贝的对象)
        * return: Object
        */
    $deepCopy: function(obj) {
        return $.extend(true, {}, obj);
    },
    /** 去除空格换行
        * params - str: String (需要去除的字符串)
        * params - type: String (spaces: 默认，去除空格，wrap: 去除回车， all: 去除空格换行)
        * return: String
        */
    $removeSpacesWrap: function(str, type) {
        switch(type) {
            case 'spaces': str = str.replace(/[ ]/g, "");break;
            case 'wrap': str = str.replace(/[\r\n]/g, "");break;
            case 'all': str = str.replace(/[ ]/g, "").replace(/[\r\n]/g, "");break;
            default: str = str.replace(/[ ]/g, "");
        }
        return str;
    }
});
$.appendLoad();
console.log([
    "                   _ooOoo_",
    "                  o8888888o",
    "                  88\" . \"88",
    "                  (| -_- |)",
    "                  O\\  =  /O",
    "               ____/`---'\\____",
    "             .'  \\\\|     |//  `.",
    "            /  \\\\|||  :  |||//  \\",
    "           /  _||||| -:- |||||-  \\",
    "           |   | \\\\\\  -  /// |   |",
    "           | \\_|  ''\\---/''  |   |",
    "           \\  .-\\__  `-`  ___/-. /",
    "         ___`. .'  /--.--\\  `. . __",
    "      .\"\" '<  `.___\\_<|>_/___.'  >'\"\".",
    "     | | :  `- \\`.;`\\ _ /`;.`/ - ` : | |",
    "     \\  \\ `-.   \\_ __\\ /__ _/   .-` /  /",
    "======`-.____`-.___\\_____/___.-`____.-'======",
    "                   `=---='",
    "         佛祖保佑       永无BUG"
].join('\n'));